#include "apue.h"
#include <time.h>
#include <sys/time.h>
#include <errno.h>

#if defined(MACOS)
#include <sys/syslimits.h>
#elif defined(SOLARIS)
#include <limits.h>
#elif defined(BSD)
#include <sys/param.h>
#endif


#define NZERO 20

unsigned long long count;
struct timeval end;

void checktime(char *str) {
	struct timeval tv;
	gettimeofday(&tv, NULL);
	if (tv.tv_sec >= end.tv_sec && tv.tv_usec >= end.tv_usec) {
		printf("%s count = %lld\n", str, count);
		exit(0);
	}
}

int main(int argc, char *argv[]) {
	pid_t pid;
	char *s;
	int ret;
	int adj = 0;
	setbuf(stdout, NULL);
	printf("NZERO = %d\n", NZERO);
	if (argc == 2) {
		adj = strtol(argv[1], NULL, 10);
	}
	gettimeofday(&end, NULL);
	end.tv_sec += 10;
	if ((pid = fork()) < 0) {
		err_sys("fork error");
	} else if (pid == 0) {
		s = "child";
		printf("current nice value in child is %d, adjusting by %d\n",
				nice(0) + NZERO, adj);
		errno = 0;
		if ((ret = nice(adj)) == -1 && errno != 0)
			err_sys("child set scheduling priority");
		printf("now child nice value is %d\n", nice(0) + NZERO);
	} else {
		s = "parent";
		printf("current nice value in parent is %d\n", nice(0) + NZERO);
	}

	for(;;) {
		if (++count == 0)
			err_quit("%s counter wrap", s);
		checktime(s);
	}
}

